<template>
	<layout>
		<!-- #ifdef MP-WEIXIN -->
		<uv-navbar :fixed="true" :title="title" />
		<!-- #endif -->

		<view class="wrap">
			<view class="top"></view>
			<view class="content">
				<view class="title">欢迎登录</view>

				<input class="u-border-bottom" type="number" v-model="mobile" placeholder="请输入手机号" />
				<view class="tips">未注册的手机号验证后自动创建账号</view>


				<view style="display: flex;">
					<view style="width: 50%;">
						<input style="height: 100rpx;" class="u-border-bottom" type="number" v-model="captcha"
							placeholder="请输入验证码" />
					</view>
					<view style="width: 50%;">
						<button style="height: 100rpx;" @tap="getCaptcha" :style="[captchaStyle]" class="getCaptcha">
							{{ captchaText }} <uv-code :seconds="seconds" @end="endCaptcha" @start="startCaptcha"
								ref="uCode" @change="changeCapcha"></uv-code>
						</button>
					</view>
				</view>

				<button @tap="submit" style="color:#fff;background-color: #f9ae3d;" type="primary" class="login">登录
				</button>

			</view>
			<view class="buttom">
				<view class="loginType">
					<!-- #ifdef MP-WEIXIN -->
					<button type="primary" size="default" class="login-btn"
						open-type="getPhoneNumber" @getphonenumber="loginForWechatMini">
						微信手机号快捷登录
					</button>
					<!-- #endif -->
					<!-- #ifdef MP-ALIPAY -->
					<button type="primary" size="default" class="login-btn alipay-btn" @tap="handleAlipayLogin">
						支付宝授权登录
					</button>
					<!-- #endif -->
				</view>
				<view class="hint" style="display: flex; align-items: center;">
					<checkbox-group @change="onChange">
						<checkbox value="agree" :checked="isChecked" />
					</checkbox-group>
					<text style="margin-left: 10rpx;">我已经阅读并遵守</text>
					<text class="link" @tap="serv(29,'用户协议')" style="margin: 0 4rpx;">《用户协议》</text>
					<text>与</text>
					<text class="link" @tap="serv(30,'隐私政策')" style="margin-left: 4rpx;">《隐私政策》</text>
				</view>
			</view>
			<uv-toast ref="uToast"></uv-toast>
		</view>
	</layout>
</template>

<script setup>
	import {
		computed,
		ref
	} from 'vue';
	import {
		onShow,
		onReady,
		onLoad
	} from '@dcloudio/uni-app';
	import {
		useMainStore
	} from '@/store/store';
	import {
		smsSend,
		userLogin,
		userLoginForWechatMini,
		alipayMiniAppLogin
	} from '@/api/auth';
	import * as util from '@/utils/util';
	import {
		mobile as testMobible
	} from '@/utils/test';
	import {
		ensurePlatformId
	} from '@/utils/platformId';
	import {
		getCurrentPlatform
	} from '@/utils/platform';
	import {
		getCurrentOpenid,
		saveAlipayOpenid,
		getLoginOpenid,
		debugOpenidInfo
	} from '@/utils/openid';

	const main = useMainStore()
	const title = ref('登录')
	const mobile = ref('')
	const captcha = ref('')
	const captchaText = ref('获取验证码')
	const password = ref('')
	const seconds = ref(60)
	const isChecked = ref(false)
	const openid = ref('')
	const uToast = ref()
	const uCode = ref()

	const captchaStyle = computed(() => {
		let style = {};
		if (mobile.value && captchaText.value == '获取验证码') {
			style.color = "#fff";
			style.backgroundColor = '#f9ae3d';
		}
		return style;
	});

	// 初始化 openid
	const initOpenid = () => {
		// 使用工具函数获取 openid
		const storedOpenid = getCurrentOpenid();
		if (storedOpenid) {
			openid.value = storedOpenid;
			console.log('初始化 openid:', storedOpenid);
		} else {
			console.log('未找到已保存的 openid');
		}
		
		// 打印调试信息
		debugOpenidInfo();
	};

	onLoad((options) => {
		console.log('=== 登录页面 onLoad 触发 ===');
		console.log('页面参数:', options);
	})

	onShow(() => {
		console.log('=== 登录页面 onShow 触发 ===');

		// 初始化 openid
		initOpenid();

		// 检查用户是否已经登录，如果已登录则直接返回
		if (main.isLogin) {
			console.log('用户已登录，直接返回上一页');
			setTimeout(() => {
				uni.navigateBack({
					fail: () => {
						// 如果无法返回，跳转到首页
						uni.reLaunch({
							url: '/pages/index/index'
						});
					}
				});
			}, 500);
			return;
		}

		console.log('登录页面就绪，等待用户手动登录');
	})



	const loginForWechatMini = async (e) => {
		if (!isChecked.value) {
			uToast.value.show({
				message: '请勾选下面协议',
				type: 'error'
			});
			return
		}
		console.log("loginForWechatMini", e);
		if (e.detail.encryptedData && e.detail.iv) {
			let data = await userLoginForWechatMini({
				encryptedData: e.detail.encryptedData,
				iv: e.detail.iv,
				openid: getLoginOpenid()
			});
			if (data) {
				main.SET_MEMBER(data.userInfo);
				main.SET_TOKEN(data.accessToken);
				main.SET_ACCESSES(data.accesses);
				uToast.value.show({
					title: '登录成功',
					type: 'success'
				});
				setTimeout(function() {
					console.log('go to back');
					// 检查页面栈，如果是第一个页面则跳转到首页
					const pages = getCurrentPages();
					console.log('当前页面栈长度:', pages.length);
					
					if (pages.length <= 1) {
						// 如果是第一个页面，跳转到首页
						console.log('当前是第一个页面，跳转到首页');
						uni.reLaunch({
							url: '/pages/index/index'
						});
					} else {
						// 有上一页，正常返回
						uni.navigateBack({
							delta: 1,
							success: function(res) {
								console.log('back success', res);
								const pages = getCurrentPages();
								const prevPage = pages[pages.length - 1];
								if (prevPage && prevPage.onLoad) {
									prevPage.onLoad();
								}
							},
							fail: function(res) {
								console.log('back fail', res);
								// 返回失败时也跳转到首页
								uni.reLaunch({
									url: '/pages/index/index'
								});
							}
						});
					}
				}, 2000);
			}
		}
	}

	const alipayMiniLogin = async () => {
		console.log('开始支付宝小程序登录流程');

		// 显示加载提示
		uni.showLoading({
			title: '登录中...',
			mask: true
		});

		try {
			// 获取支付宝授权码
			const authResult = await new Promise((resolve, reject) => {
				my.getAuthCode({
					scopes: ['auth_user'],
					success: (res) => {
						console.log('获取授权码成功:', res.authCode);
						resolve(res);
					},
					fail: (err) => {
						console.error('获取授权码失败:', err);
						reject(err);
					}
				});
			}); 
			
			// 调用后端登录接口
			const result = await alipayMiniAppLogin({
				code: authResult.authCode
			});

			console.log('支付宝登录接口返回:', result);

			// 检查登录是否成功
			if (result && result.accessToken) {
				// 保存用户信息到store
				main.SET_MEMBER(result.userInfo);
				main.SET_TOKEN(result.accessToken);
				main.SET_ACCESSES(result.accesses || []);

				// 使用工具函数保存 openid
				if (result.buyerId) {
					console.log('登录成功，保存 buyerId 为 openid:', result.buyerId);
					saveAlipayOpenid(result);
					openid.value = result.buyerId;
				}

				uni.hideLoading();

				// 显示登录成功提示
				uToast.value.show({
					title: '登录成功',
					type: 'success'
				});

				// 延迟返回上一页
				setTimeout(() => {
					// 检查页面栈，如果是第一个页面则跳转到首页
					const pages = getCurrentPages();
					console.log('当前页面栈长度:', pages.length);
					
					if (pages.length <= 1) {
						// 如果是第一个页面，跳转到首页
						console.log('当前是第一个页面，跳转到首页');
						uni.reLaunch({
							url: '/pages/index/index'
						});
					} else {
						// 有上一页，正常返回
						uni.navigateBack({
							delta: 1,
							success: (res) => {
								console.log('返回上一页成功', res);
								// 刷新上一页
								const pages = getCurrentPages();
								if (pages.length > 1) {
									const prevPage = pages[pages.length - 2];
									if (prevPage && prevPage.onLoad) {
										prevPage.onLoad();
									}
								}
							},
							fail: (res) => {
								console.log('返回上一页失败', res);
								// 返回失败时也跳转到首页
								uni.reLaunch({
									url: '/pages/index/index'
								});
							}
						});
					}
				}, 1500);
			} else {
				throw new Error('登录返回数据格式错误');
			}

		} catch (err) {
			uni.hideLoading();
			console.error('支付宝登录失败:', err);

			// 显示错误提示
			const errorMsg = err.msg || err.message || '登录失败，请重试';
			uToast.value.show({
				message: errorMsg,
				type: 'error'
			});
		}
	};




	// 获取验证码
	const getCaptcha = async () => {
		if (testMobible(mobile.value) == false) {
			uToast.value.show({
				message: '手机号码格式不对',
				type: 'error'
			});
			return
		}
		uCode.value.start()
		let data = await smsSend({
			mobile: mobile.value,
			scene: 1
		})
		if (data) {
			uToast.value.show({
				message: '验证码发送成功',
				type: 'success'
			});
		}
	}
	// 验证码开始
	const startCaptcha = () => {
		console.log('start')
	}
	// 验证码结束
	const endCaptcha = () => {
		console.log('end')
		captchaText.value = '获取验证码';
	}
	const changeCapcha = (text) => {
		console.log('change:' + text)
		captchaText.value = text;
	}
	// 提交
	const submit = () => {

		if (testMobible(mobile.value) == false) {
			uToast.value.show({
				message: '手机号码格式不对',
				type: 'error'
			});
			return
		}

		if (!isChecked.value) {
			uToast.value.show({
				message: '请勾选下面协议',
				type: 'error'
			});
			return
		}

		login()

	}
	// 登录
	const login = async () => {
		console.log('=== 开始手机号验证码登录 ===');
		
		// 获取当前平台标识
		const currentPlatform = getCurrentPlatform();
		console.log('当前平台:', currentPlatform);
		
		// 使用工具函数获取 openid
		const currentOpenid = getLoginOpenid();
		console.log('当前 openid:', currentOpenid);
		
		// 根据平台设置 from 参数
		let from = 'h5'; // 默认值
		if (currentPlatform === 'alipay') {
			from = 'alipay';
		} else if (currentPlatform === 'wechat') {
			from = 'wechat';
		}
		
		// 构建登录参数 - 根据平台类型设置正确的字段名
		let loginParams = {
			mobile: mobile.value,
			code: captcha.value,
			from: from
		};
		
		// 根据平台类型设置正确的ID字段
		if (from === 'wechat' && currentOpenid) {
			loginParams.openid = currentOpenid;  // 微信平台使用 openid
		} else if (from === 'alipay' && currentOpenid) {
			loginParams.buyerId = currentOpenid; // 支付宝平台使用 buyerId
		}
		
		console.log('登录参数:', loginParams);
		
		let data = await userLogin(loginParams)
		
		if (data) {
			uni.setStorage({
				key: 'userinfo',
				data: data.userInfo
			});
			uni.setStorage({
				key: 'accessToken',
				data: data.accessToken
			});
			main.SET_MEMBER(data.userInfo);
			main.SET_TOKEN(data.accessToken);
			main.SET_ACCESSES(data.accesses);

			// 显示登录成功提示
			uToast.value.show({
				message: '登录成功',
				type: 'success'
			});

			// 登录成功后自动补充平台ID
			try {
				await ensurePlatformId('auto');
				console.log('平台ID补充完成');
			} catch (error) {
				console.log('平台ID补充失败，但不影响登录:', error);
			}

			setTimeout(function() {
				// 检查页面栈，如果是第一个页面则跳转到首页
				const pages = getCurrentPages();
				console.log('当前页面栈长度:', pages.length);
				
				if (pages.length <= 1) {
					// 如果是第一个页面，跳转到首页
					console.log('当前是第一个页面，跳转到首页');
					uni.reLaunch({
						url: '/pages/index/index'
					});
				} else {
					// 有上一页，正常返回
					uni.navigateBack({
						delta: 1,
						success: (res) => {
							console.log('返回上一页成功', res);
							// 刷新上一页
							const pages = getCurrentPages();
							if (pages.length > 1) {
								const prevPage = pages[pages.length - 2];
								if (prevPage && prevPage.onLoad) {
									prevPage.onLoad();
								}
							}
						},
						fail: (res) => {
							console.log('返回上一页失败', res);
							// 返回失败时也跳转到首页
							uni.reLaunch({
								url: '/pages/index/index'
							});
						}
					});
				}
			}, 2000);
		}
	}

	const serv = (id, name) => {
		uni.navigateTo({
			url: '/pages/components/pages/mine/content?id=' + id + '&name=' + name
		})
	}
	const onChange = (e) => {
		isChecked.value = e.detail.value.includes('agree')
	}

	// 处理支付宝登录按钮点击
	const handleAlipayLogin = () => {
		// 检查是否同意协议
		if (!isChecked.value) {
			uToast.value.show({
				message: '请先勾选并同意用户协议和隐私政策',
				type: 'error'
			});
			return;
		}

		// 开始支付宝登录流程
		alipayMiniLogin();
	}

</script>

<style lang="scss" scoped>
	.wrap {
		background-color: #ffffff;
		font-size: 28rpx;
		position: relative;
		height: 100%;
		/* #ifdef MP-ALIPAY */
		padding-top: env(safe-area-inset-top);
		min-height: 100vh;
		box-sizing: border-box;
		/* #endif */

		.content {
			width: 600rpx;
			margin: 0 auto;

			.title {
				text-align: left;
				font-size: 60rpx;
				font-weight: 500;
				margin-bottom: 100rpx;
			}

			input {
				text-align: left;
				margin-bottom: 10rpx;
				padding-bottom: 6rpx;
			}

			.tips {
				color: $uv-info;
				margin-bottom: 60rpx;
				margin-top: 8rpx;
			}

			.getCaptcha {
				background-color: rgb(253, 243, 208);
				color: $uv-tips-color;
				border: none;
				font-size: 30rpx;
				padding: 12rpx 0;

				&::after {
					border: none;
				}
			}

			.login {
				background-color: rgb(253, 243, 208);
				color: $uv-tips-color;
				border: none;
				font-size: 30rpx;
				padding: 12rpx 0;
				margin-top: 40rpx;

				&::after {
					border: none;
				}
			}

			.alternative {
				color: $uv-tips-color;
				display: flex;
				justify-content: space-between;
				margin-top: 30rpx;
			}
		}

		.buttom {
			//position: absolute;
			bottom: 0;

			//display: flex;
			//flex-direction: column;
			//align-items: center;
			//justify-content: center;
			.loginType {
				padding: 80rpx;
				//justify-content:space-between;

				.login-btn {
					background-color: #1aad19 !important;
					width: 100%;
					border-radius: 50rem !important;
					display: flex;
					align-items: center;
					justify-content: center;
					padding: 10rpx 0;
					text-align: center;

					image {
						width: 36rpx;
						height: 30rpx;
						margin-right: 10rpx;
						vertical-align: middle;
					}
				}

				.alipay-btn {
					background-color: #1678ff !important;
					margin-top: 20rpx;
				}
			}

			.hint {
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 20rpx 40rpx;
				font-size: 20rpx;
				color: $uv-tips-color;

				.link {
					color: $uv-warning;
				}
			}
		}
	}
</style>